<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票估值数据可视化</title>
    <!-- 引入Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <!-- 引入Font Awesome -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <!-- 引入ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
            background-color: #f8f9fa;
        }
        .container {
            margin-top: 20px;
            max-width: 1400px;
        }
        .card {
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #e9ecef;
            border-radius: 8px 8px 0 0;
            padding: 15px 20px;
            font-weight: 600;
            color: #333;
        }
        .card-body {
            padding: 20px;
        }
        .chart-container {
            width: 100%;
            height: 400px;
            margin-bottom: 20px;
        }
        .search-form {
            margin-bottom: 20px;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
        .btn-success {
            background-color: #28a745;
            border-color: #28a745;
        }
        .btn-success:hover {
            background-color: #1e7e34;
            border-color: #1e7e34;
        }
        .btn-danger {
            background-color: #dc3545;
            border-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
            border-color: #c82333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .table-wrapper {
            max-height: 500px;
            overflow-y: auto;
        }
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            position: sticky;
            top: 0;
            z-index: 1;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            display: none;
        }
        .loading-content {
            text-align: center;
        }
        .loading-spinner {
            font-size: 48px;
            color: #007bff;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .stats-card {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        .stats-value {
            font-size: 24px;
            font-weight: 700;
            color: #007bff;
        }
        .stats-label {
            font-size: 14px;
            color: #6c757d;
            margin-top: 5px;
        }
        .alert {
            margin-top: 15px;
        }
        .tab-content {
            padding: 20px 0;
        }
        .nav-tabs .nav-link.active {
            color: #007bff;
            border-color: #dee2e6 #dee2e6 #fff;
            font-weight: 600;
        }
        .date-range {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .date-range input {
            flex: 1;
        }
        .download-buttons {
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <!-- 加载中遮罩层 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-content">
            <i class="fa fa-circle-o-notch fa-spin loading-spinner"></i>
            <p id="loadingText" class="mt-3">数据加载中...</p>
        </div>
    </div>

    <div class="container">
        <div class="card">
            <div class="card-header">
                <i class="fa fa-line-chart mr-2"></i>股票估值数据可视化
            </div>
            <div class="card-body">
                <!-- 搜索表单 -->
                <div class="search-form">
                    <div class="row">
                        <div class="col-md-3 form-group">
                            <label for="securityCode">证券代码</label>
                            <input type="text" id="securityCode" class="form-control" placeholder="请输入证券代码，如：000001" value="000001">
                        </div>
                        <div class="col-md-4 form-group">
                            <label for="dateRange">日期范围</label>
                            <div class="date-range">
                                <input type="date" id="startDate" class="form-control" value="2023-01-01">
                                <span>至</span>
                                <input type="date" id="endDate" class="form-control" value="2023-12-31">
                            </div>
                        </div>
                        <div class="col-md-2 form-group">
                            <label>&nbsp;</label>
                            <button id="searchBtn" class="btn btn-primary btn-block"><i class="fa fa-search mr-1"></i>查询数据</button>
                        </div>
                        <div class="col-md-2 form-group">
                            <label>&nbsp;</label>
                            <button id="fetchBtn" class="btn btn-success btn-block"><i class="fa fa-download mr-1"></i>抓取数据</button>
                        </div>
                    </div>
                </div>

                <!-- 数据统计卡片 -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="stats-card">
                            <div class="stats-value" id="totalRecords">0</div>
                            <div class="stats-label">总记录数</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card">
                            <div class="stats-value" id="avgPe">0.00</div>
                            <div class="stats-label">平均市盈率</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card">
                            <div class="stats-value" id="maxPe">0.00</div>
                            <div class="stats-label">最高市盈率</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card">
                            <div class="stats-value" id="minPe">0.00</div>
                            <div class="stats-label">最低市盈率</div>
                        </div>
                    </div>
                </div>

                <!-- 图表和表格选项卡 -->
                <ul class="nav nav-tabs" id="dataTabs" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="chart-tab" data-toggle="tab" href="#chart" role="tab" aria-controls="chart" aria-selected="true">
                            <i class="fa fa-bar-chart mr-1"></i>图表展示
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="table-tab" data-toggle="tab" href="#table" role="tab" aria-controls="table" aria-selected="false">
                            <i class="fa fa-table mr-1"></i>数据表格
                        </a>
                    </li>
                </ul>

                <!-- 选项卡内容 -->
                <div class="tab-content" id="dataTabsContent">
                    <!-- 图表展示区域 -->
                    <div class="tab-pane fade show active" id="chart" role="tabpanel" aria-labelledby="chart-tab">
                        <!-- 市盈率趋势图 -->
                        <div class="chart-container" id="peTrendChart"></div>
                        
                        <!-- 下载按钮 -->
                        <div class="download-buttons text-center">
                            <button id="downloadChartBtn" class="btn btn-secondary mr-2">
                                <i class="fa fa-download mr-1"></i>下载图表
                            </button>
                            <button id="downloadDataBtn" class="btn btn-secondary">
                                <i class="fa fa-file-excel-o mr-1"></i>下载数据
                            </button>
                        </div>
                    </div>

                    <!-- 数据表格区域 -->
                    <div class="tab-pane fade" id="table" role="tabpanel" aria-labelledby="table-tab">
                        <div class="table-wrapper">
                            <table class="table table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>证券代码</th>
                                        <th>证券名称</th>
                                        <th>交易日期</th>
                                        <th>指标类型</th>
                                        <th>指标值</th>
                                        <th>数据来源</th>
                                        <th>创建时间</th>
                                        <th>更新时间</th>
                                    </tr>
                                </thead>
                                <tbody id="dataTableBody">
                                    <!-- 表格数据将通过JavaScript动态填充 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
    <!-- 引入Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // 全局变量
        let currentData = [];
        let peTrendChart = null;

        // 初始化页面
        $(document).ready(function() {
            // 初始化ECharts图表
            initCharts();
            
            // 绑定事件
            bindEvents();
            
            // 默认查询数据
            searchData();
        });

        // 初始化图表
        function initCharts() {
            // 初始化市盈率趋势图
            peTrendChart = echarts.init(document.getElementById('peTrendChart'));
            
            // 设置默认配置
            const defaultOption = {
                title: {
                    text: '市盈率趋势图',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function(params) {
                        let result = params[0].axisValue + '<br/>';
                        params.forEach(function(param) {
                            result += param.marker + param.seriesName + ': ' + param.value.toFixed(2) + '<br/>';
                        });
                        return result;
                    }
                },
                legend: {
                    data: ['市盈率'],
                    bottom: 0
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [],
                    axisLabel: {
                        interval: 'auto',
                        rotate: 45
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '市盈率',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                series: [
                    {
                        name: '市盈率',
                        type: 'line',
                        smooth: true,
                        data: [],
                        lineStyle: {
                            color: '#007bff',
                            width: 2
                        },
                        itemStyle: {
                            color: '#007bff'
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: 'rgba(0, 123, 255, 0.3)'
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(0, 123, 255, 0.05)'
                                }
                            ])
                        }
                    }
                ]
            };
            
            peTrendChart.setOption(defaultOption);
            
            // 响应窗口大小变化
            window.addEventListener('resize', function() {
                peTrendChart.resize();
            });
        }

        // 绑定事件
        function bindEvents() {
            // 查询按钮点击事件
            $('#searchBtn').click(function() {
                searchData();
            });
            
            // 抓取数据按钮点击事件
            $('#fetchBtn').click(function() {
                fetchData();
            });
            
            // 下载图表按钮点击事件
            $('#downloadChartBtn').click(function() {
                downloadChart();
            });
            
            // 下载数据按钮点击事件
            $('#downloadDataBtn').click(function() {
                downloadData();
            });
            
            // 回车键触发查询
            $('#securityCode, #startDate, #endDate').keypress(function(e) {
                if (e.which === 13) {
                    searchData();
                }
            });
            
            // 选项卡切换事件
            $('#dataTabs a').click(function(e) {
                e.preventDefault();
                $(this).tab('show');
                
                // 如果切换到图表选项卡，重新渲染图表
                if ($(this).attr('aria-controls') === 'chart') {
                    setTimeout(function() {
                        peTrendChart.resize();
                    }, 100);
                }
            });
        }

        // 显示加载状态
        function showLoading(text = '数据加载中...') {
            $('#loadingText').text(text);
            $('#loadingOverlay').show();
        }

        // 隐藏加载状态
        function hideLoading() {
            $('#loadingOverlay').hide();
        }

        // 显示消息提示
        function showMessage(type, message) {
            const alertType = type === 'success' ? 'alert-success' : 
                             type === 'error' ? 'alert-danger' : 
                             type === 'warning' ? 'alert-warning' : 'alert-info';
            
            const alertHtml = `
                <div class="alert ${alertType} alert-dismissible fade show" role="alert">
                    ${message}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            `;
            
            // 移除现有的消息
            $('.alert').remove();
            
            // 添加新消息
            $('.card-body').prepend(alertHtml);
            
            // 3秒后自动关闭
            setTimeout(function() {
                $('.alert').alert('close');
            }, 3000);
        }

        // 查询数据
        function searchData() {
            const securityCode = $('#securityCode').val().trim();
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();
            
            if (!securityCode) {
                showMessage('warning', '请输入证券代码');
                return;
            }
            
            if (!startDate || !endDate) {
                showMessage('warning', '请选择日期范围');
                return;
            }
            
            showLoading('正在查询数据...');
            
            // 构建查询URL
            const apiUrl = `/api/stockpe/query?securityCode=${securityCode}&startDate=${startDate}&endDate=${endDate}`;
            
            // 发送请求
            $.ajax({
                url: apiUrl,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    hideLoading();
                    
                    if (response.code === 200) {
                        currentData = response.data || [];
                        updateStats(currentData);
                        updateChart(currentData);
                        updateTable(currentData);
                        
                        if (currentData.length === 0) {
                            showMessage('info', '未查询到数据，请尝试先抓取数据');
                        }
                    } else {
                        showMessage('error', `查询失败：${response.message || '未知错误'}`);
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', `查询异常：${xhr.responseText || error}`);
                }
            });
        }

        // 抓取数据
        function fetchData() {
            const securityCode = $('#securityCode').val().trim();
            
            if (!securityCode) {
                showMessage('warning', '请输入证券代码');
                return;
            }
            
            showLoading('正在抓取数据...');
            
            // 构建抓取URL
            const apiUrl = `/api/stockpe/fetch/${securityCode}`;
            
            // 发送请求
            $.ajax({
                url: apiUrl,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    hideLoading();
                    
                    if (response.code === 200) {
                        showMessage('success', `数据抓取成功，处理了${response.data.processedCount}条记录`);
                        // 自动刷新数据
                        searchData();
                    } else {
                        showMessage('error', `抓取失败：${response.message || '未知错误'}`);
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', `抓取异常：${xhr.responseText || error}`);
                }
            });
        }

        // 更新统计信息
        function updateStats(data) {
            if (!data || data.length === 0) {
                $('#totalRecords').text('0');
                $('#avgPe').text('0.00');
                $('#maxPe').text('0.00');
                $('#minPe').text('0.00');
                return;
            }
            
            // 计算统计值
            const totalRecords = data.length;
            const values = data.map(item => parseFloat(item.indicatorValue));
            const avgPe = values.reduce((sum, val) => sum + val, 0) / values.length;
            const maxPe = Math.max(...values);
            const minPe = Math.min(...values);
            
            // 更新DOM
            $('#totalRecords').text(totalRecords.toLocaleString());
            $('#avgPe').text(avgPe.toFixed(2));
            $('#maxPe').text(maxPe.toFixed(2));
            $('#minPe').text(minPe.toFixed(2));
        }

        // 更新图表
        function updateChart(data) {
            if (!data || data.length === 0) {
                peTrendChart.setOption({
                    xAxis: { data: [] },
                    series: [{ data: [] }]
                });
                return;
            }
            
            // 按日期排序
            const sortedData = [...data].sort((a, b) => new Date(a.tradeDate) - new Date(b.tradeDate));
            
            // 准备图表数据
            const dates = sortedData.map(item => new Date(item.tradeDate).toLocaleDateString('zh-CN'));
            const peValues = sortedData.map(item => parseFloat(item.indicatorValue));
            
            // 更新图表
            peTrendChart.setOption({
                xAxis: {
                    data: dates
                },
                series: [
                    {
                        data: peValues
                    }
                ]
            });
        }

        // 更新表格
        function updateTable(data) {
            const tableBody = $('#dataTableBody');
            tableBody.empty();
            
            if (!data || data.length === 0) {
                const emptyRow = `
                    <tr>
                        <td colspan="9" class="text-center">暂无数据</td>
                    </tr>
                `;
                tableBody.append(emptyRow);
                return;
            }
            
            // 按日期排序
            const sortedData = [...data].sort((a, b) => new Date(b.tradeDate) - new Date(a.tradeDate));
            
            // 填充表格
            sortedData.forEach((item, index) => {
                const row = `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${item.securityCode}</td>
                        <td>${item.securityName || '-'}</td>
                        <td>${new Date(item.tradeDate).toLocaleDateString('zh-CN')}</td>
                        <td>${item.indicatorType}</td>
                        <td>${parseFloat(item.indicatorValue).toFixed(2)}</td>
                        <td>${item.dataSource || '-'}</td>
                        <td>${item.createTime ? new Date(item.createTime).toLocaleString('zh-CN') : '-'}</td>
                        <td>${item.updateTime ? new Date(item.updateTime).toLocaleString('zh-CN') : '-'}</td>
                    </tr>
                `;
                tableBody.append(row);
            });
        }

        // 下载图表
        function downloadChart() {
            if (!peTrendChart) {
                showMessage('warning', '图表未初始化');
                return;
            }
            
            try {
                // 获取图表的Base64图片
                const url = peTrendChart.getDataURL({
                    type: 'png',
                    pixelRatio: 2,
                    backgroundColor: '#fff'
                });
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = url;
                link.download = `市盈率趋势图_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.png`;
                link.click();
                
                showMessage('success', '图表下载成功');
            } catch (error) {
                showMessage('error', `图表下载失败：${error.message}`);
            }
        }

        // 下载数据
        function downloadData() {
            if (!currentData || currentData.length === 0) {
                showMessage('warning', '暂无数据可下载');
                return;
            }
            
            try {
                // 准备CSV数据
                let csvContent = '序号,证券代码,证券名称,交易日期,指标类型,指标值,数据来源,创建时间,更新时间\n';
                
                currentData.forEach((item, index) => {
                    const row = [
                        index + 1,
                        item.securityCode || '',
                        item.securityName || '',
                        item.tradeDate ? new Date(item.tradeDate).toLocaleDateString('zh-CN') : '',
                        item.indicatorType || '',
                        parseFloat(item.indicatorValue).toFixed(2) || '',
                        item.dataSource || '',
                        item.createTime ? new Date(item.createTime).toLocaleString('zh-CN') : '',
                        item.updateTime ? new Date(item.updateTime).toLocaleString('zh-CN') : ''
                    ].map(value => `"${value}"`).join(',');
                    
                    csvContent += row + '\n';
                });
                
                // 创建Blob对象
                const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
                
                // 创建下载链接
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `市盈率数据_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                showMessage('success', '数据下载成功');
            } catch (error) {
                showMessage('error', `数据下载失败：${error.message}`);
            }
        }
    </script>
</body>
</html>